<?php
namespace app\common\model;
use think\Request;
use think\Db;
use think\Cache;

/**
 * 用户认证申请模型
 */
class StoreApply extends BaseModel
{
    protected $name = 'store_apply';

    /**
     * 认证类型
     */
    public function getApplyModeAttr($value)
    {
        $status = [10 => '商户入驻', 20 => '支付认证', 30 => '代理认证', 40 => '实名认证', 50 => '小程序申请'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 关联用户详情表
     */
    public function details()
    {
        return $this->hasOne('StoreDetail', 'store_user_id', 'store_user_id');
    }

    /**
     * 支付类型
     */
    public function getPayModeAttr($value)
    {
        $status = [10 => '微信', 20 => '支付宝'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 小程序类型
     */
    public function getAppModeAttr($value)
    {
        $status = [10 => '微信', 20 => '支付宝'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 认证类型
     */
    public function getAuthModeAttr($value)
    {
        $status = [10 => '工商', 20 => '个人'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 门店类型
     */
    public function getShopModeAttr($value)
    {
        $status = [10 => '单门店', 20 => '多门店'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 代理级别
     */
    public function getAgentModeAttr($value)
    {
        $status = [10 => '区县', 20 => '市级', 30 => '省级'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 付款状态
     */
    public function getPayStatusAttr($value)
    {
        $status = [10 => '待付款', 20 => '已付款', 30 => '免费认证'];
        return ['text' => $status[$value], 'value' => $value];
    }

   /**
     * 当前类型
     */
    public function getApplyStatusAttr($value)
    {
        $status = [10 => '待审核', 20 => '验证中', 30 => '认证成功', 40 => '被驳回'];
        return ['text' => $status[$value], 'value' => $value];
    }
    /**
     * 获取认证申请列表
     */
    public function getList($dataType='',$agent_id='',$store_user_id='')
    {
        $where = [];
        !empty($dataType) && $where['apply_mode'] = $dataType;
        !empty($agent_id) && $where['agent_id'] = $agent_id;
        !empty($store_user_id) && $where['store_user_id'] = $store_user_id;
        // 执行查询
        return $this->useGlobalScope(false)
            ->with(['details'])
            ->where($where)
            ->order('store_apply_id','desc')
            ->paginate(15, false, ['query' => Request::instance()->request()]);
    }
    
    /**
     * 详情
     */
    public static function detail($store_apply_id)
    {
        return self::useGlobalScope(false)->with(['details'])->where([
            'store_apply_id' => $store_apply_id
        ])->find();
    }

    /**
     * 详情
     */
    public static function getDetail($where = [])
    {
        return self::useGlobalScope(false)->where($where)->find();
    }

    /**
     * 详情
     */
    public static function getApply($apply_mode,$store_user_id)
    {
        return self::useGlobalScope(false)->with(['details'])->where([
            'store_user_id' => $store_user_id,
            'apply_mode' => $apply_mode
        ])->find();
    }

    /**
     * 添加
     */
    public function add($data=[])
    {
        $title = '';
        $data['pay_status'] = 30; //付款状态
        $data['pay_time'] = time(); //付款时间 
        // 开启事务
        Db::startTrans();
        try {
            if($data['apply_mode'] == 10){
                $title = "平台入驻";
            }
            if($data['apply_mode'] == 20){
                $title = "支付商户号";
            }
            if($data['apply_mode'] == 30){
                $title = "区域代理";
            }
            if($data['apply_mode'] == 40){
                $title = "实名认证";
            }
            //用户添加，判断是否扣费
            if($data['apply_mode'] == 50){
                $title = "注册小程序";
                $values = WebSet::getItem('register');
                if($values['examine']>0){
                    //如果需要扣费
                    $store = StoreUser::detail($data['store_user_id']);
                    if($store['wallet'] < $values['examine']){
                        $this->error = '您账户余额不足？需要支付￥'. $values['examine'] .'元审核费！';
                        return false;
                    }
                    $wallet = $store['wallet'] - $values['examine'];
                    $store->wallet = $wallet;
                    $store->save();
                    $order = new WebOrder;
                    $order->save([
                        'order_no' => orderNo(),
                        'order_type' => 20, //扣费
                        'pay_price' => $values['examine'],
                        'pay_status' => 20, 
                        'pay_time' => time(),
                        'purpose' => '小程序注册',
                        'affair_id' => $data['wxapp_id'],
                        'agent_id' => $store['agent_id'],
                        'store_user_id' => $store['store_user_id']                  
                    ]);
                    $data['pay_status'] = 20; //付款状态
                    $data['pay_time'] = time(); //付款时间
                    //账户资金变动提醒
                    sand_account_change_msg('小程序审核费',$values['examine'],$wallet,$data['store_user_id']);
                }
            }
            // 添加
            $this->allowField(true)->save($data);
            // 更新资料
            $this->updateDetail($data);
            //申请受理通知
            sand_apply_msg($data['details']['id_card_name'],$title,$data['store_user_id']);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 编辑
     */
    public function edit($data)
    {
        // 开启事务
        Db::startTrans();
        try {
            // 添加
            $this->allowField(true)->save($data);
            // 更新资料
            $this->updateDetail($data);
            //如果是注册小程序或者平台入驻
            if($data['apply_status']==20){
                //提交到微信审核
                $result = $this->action();
                if($result['errcode']!=0){
                    $this->error = wx_err_msg($result['errcode']);
                    return false;
                }
                sand_examine_msg($this->store_apply_id,$this->apply_mode['text'] . ' - 验证成功','待视频认证',$this->store_user_id);
            }
            //如果审核通过
            if($data['apply_status']==30){
                //如果是支付申请
                if($this->apply_mode['value']==20){
                    if(empty($data['mchid'])){
                        $this->error = '商户号不可为空';
                        return false;
                    }
                    if($payment = Setting::detail('payment')){
                        $payment->delete();
                    }else{
                        $payment = new Setting;
                    }
                    $payment->save([
                        'key' => 'payment',
                        'describe' => '支付设置',
                        'values' => [
                            'wx' => [
                                'is_sub' => 1, //是否为特约商户
                                'mchid' => $data['mchid'],//商户号
                                'apikey' => '',//密钥
                                'cert_pem' => '', //apiclient_cert.pem 证书
                                'key_pem' => '' //apiclient_key.pem 密钥
                            ],
                            'postpaid' => [0,0,0]
                        ],
                        'wxapp_id' => $this->wxapp_id
                    ]);
                    Cache::rm('setting_' . $this->wxapp_id);
                }
                //如果是代理认证
                if($this->apply_mode['value']==30){
                    $store = new StoreUser;
                    $store->save(['is_agent' => 1],['store_user_id' => $this->store_user_id]);
                }
                sand_examine_msg($this->store_apply_id,$this->apply_mode['text'] . ' - 审核通过','感谢您的支持',$this->store_user_id);
            }
            //如果被驳回
            if($data['apply_status']==40){
                if(empty($data['reject'])){
                    $this->error = '驳回原因不可为空';
                    return false;
                }
                sand_examine_msg($this->store_apply_id,$this->apply_mode['text'] . ' - 被驳回','待补充资料',$this->store_user_id);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 更新资料
    */ 
    private function updateDetail($data)
    {
        if(!isset($data['store_user_id'])){
            $data['store_user_id'] = $this->store_user_id;
        }
        if($detail = StoreDetail::getDetail(['store_user_id' => $data['store_user_id']])){
            return $detail->save($data['details']);
        }
        $data['details']['store_user_id'] = $data['store_user_id'];
        // 显式指定当前操作为新增操作
        $detail = new StoreDetail;
        return $detail->save($data['details']);
    }

    /**
     * 微信小程序提交申请
     */
    private function action()
    {
        $config = Config::detail();    //获取第三方配置
        $url = 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token='.$config['component_access_token'];
        $data =[
            'name' => $this['details']['merchant_name'],     //营业执照名称
            'code' => $this['details']['license_number'], //统一社会信用代码
            'code_type' => 1,   // 企业代码类型（1：统一社会信用代码， 2：组织机构代码，3：营业执照注册号）
            'legal_persona_wechat' => $this['details']['legal_persona_wechat'], //所有人微信
            'legal_persona_name' => $this['details']['id_card_name'],  //所有人姓名
            'component_phone' => '' //第三方联系电话
        ];
        $result = json_decode(http_post($url,$data),true);
        return $result;
    }

    /**
     * 特约商户进件
     */
    public function applyment($data)
    {
        $account_name = $data['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL' ? $data['id_card_name'] : $data['merchant_name'];//开户名称
        return [
            'business_code' => $this['business_code'],          //业务申请编号
            'contact_info' => [             //超级管理员信息（全部加密）
                'contact_name' => $this->getEncrypt($data['id_card_name']),//姓名
                'contact_id_number' => $this->getEncrypt($data['id_card_number']),//身份证号
                //'openid' => '',   //微信号
                'mobile_phone' => $this->getEncrypt($data['mobile_phone']),     //手机号
                'contact_email' => $this->getEncrypt($data['contact_email'])        //邮箱
            ],
            'subject_info' => [         //主体资料
                'subject_type' => $data['subject_type'],        //主体类型
                'business_license_info' => [    //营业执照
                    'license_copy' => 'MediaID',        //营业执照照片
                    'license_number' => $data['license_number'],    //统一社会信用代码
                    'merchant_name' => $data['merchant_name'],      //营业执照名称
                    'legal_person' => $data['id_card_name']     //法人姓名
                ],  
                'identity_info' => [    //法人身份证件
                    'id_doc_type' => 'IDENTIFICATION_TYPE_IDCARD',
                    'id_card_info' => [ //身份证信息
                        'id_card_copy' => 'MediaID',    //正面图
                        'id_card_national' => 'MediaID',    //反面图
                        'id_card_name' => $this->getEncrypt($data['id_card_name']), //姓名（加密）
                        'id_card_number' => $this->getEncrypt($data['id_card_number']), //号码（加密）
                        'card_period_begin' => $data['card_period_begin'],  //有效期开始时间
                        'card_period_end' => $data['card_period_end']   //结束时间
                    ],
                    'owner' => true,        //法人是否为受益人
                ]
            ],
            'business_info' => [        //经营资料
                'merchant_shortname' => $data['merchant_shortname'],        //商户简称
                'service_phone' => $data['mobile_phone'],   //客服电话如：051699999999
                'sales_info' => [       //经营场景
                    'sales_scenes_type' => [
                        'SALES_SCENES_MINI_PROGRAM' //小程序
                    ],
                    'mini_program_info' => [//小程序场景
                        'mini_program_sub_appid' => ''  //商家小程序APPID
                    ]
                ]
            ],
            'settlement_info' => [      //结算规格
                'settlement_id' => $data['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL' ? '719' : '716',      //入驻结算规则ID,个体户=719 企业=716
                'qualification_type' => $data['qualification_type'],    //所属行业
                'qualifications' => [   //特殊行业资质图片 如食品经营许可证
                    'MediaID'
                ]
            ],
            'bank_account_info' => [    //结算银行账户
                'bank_account_type' => $data['subject_type'] == 'SUBJECT_TYPE_INDIVIDUAL' ? 'BANK_ACCOUNT_TYPE_PERSONAL' : 'BANK_ACCOUNT_TYPE_CORPORATE',       //账户类型 BANK_ACCOUNT_TYPE_CORPORATE：对公银行账户 BANK_ACCOUNT_TYPE_PERSONAL：经营者个人银行卡
                'account_name' => $this->getEncrypt($account_name), //开户名称(加密) 个体法人名称/公司全称
                'account_bank' => $data['account_bank'],        //开户银行 如工商银行
                'bank_address_code' => $data['bank_address_code'],      //开户银行省市编码
                'bank_name' => $data['bank_name'],  //开户银行全称
                'account_number' => $this->getEncrypt($data['account_number'])  //银行账号(加密)
            ]
        ];
    }

}
